<template>
  <el-form
    ref="formRef"
    :model="formData"
    :rules="formRules"
    label-width="140px"
    v-loading="formLoading"
  >
    <CardTitle :title="t('template.stageRules.baseTitle')" class="block mb-10px" />
    <!-- 评选方式 1投票 2排序 3推荐 -->
    <el-form-item :label="t('templateRule.fields.judgeType')" prop="judgeType">
      <el-select
        v-model="formData.judgeType"
        :placeholder="t('common.selectTextPlaceholder') + t('templateRule.fields.judgeType')"
        @change="cleanCoordinateIfTypeSort"
      >
        <el-option :label="t('judgeType.vote')" value="1" />
        <el-option :label="t('judgeType.sort')" value="2" :disabled="formData.judgeStage === '1'" />
        <el-option :label="t('judgeType.score')" value="3" disabled />
      </el-select>
    </el-form-item>
    <!-- 是否需要答辩 -->
    <el-form-item :label="t('templateRule.fields.isDebate')" prop="isDebate">
      <el-radio-group v-model="formData.isDebate">
        <el-radio :value="true">{{ t('common.yes') }}</el-radio>
        <el-radio :value="false">{{ t('common.no') }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 名额类型 -->
    <el-form-item :label="t('templateRule.fields.amountType')" prop="amountType">
      <el-select
        v-model="formData.amountType"
        :placeholder="t('common.selectTextPlaceholder') + t('templateRule.fields.amountType')"
        @change="onAmountTypeChange"
      >
        <el-option :label="t('amountType.onlyDoctor')" :value="1" />
        <el-option :label="t('amountType.onlyMaster')" :value="2" />
        <el-option
          :label="t('amountType.masterAndDoctorCoordinate')"
          :value="3"
          :disabled="formData.judgeType === '2'"
        />
        <el-option :label="t('amountType.masterAndDoctorMerge')" :value="4" />
      </el-select>
    </el-form-item>
    <!-- 平票是否直接晋级下个阶段 -->
    <el-form-item
      v-if="isInitial"
      :label="t('templateRule.fields.isDrawToNext')"
      prop="isDrawToNext"
    >
      <el-radio-group v-model="formData.isDrawToNext">
        <el-radio :value="true">{{ t('common.yes') }}</el-radio>
        <el-radio :value="false">{{ t('common.no') }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 是否按专业分组评审 -->
    <el-form-item v-if="false" :label="t('templateRule.fields.isMajorGroup')" prop="isMajorGroup">
      <el-radio-group
        v-model="formData.isMajorGroup"
        @change="(val: boolean) => resetMajorGroupSettings(val)"
      >
        <el-radio :value="true">{{ t('common.yes') }}</el-radio>
        <el-radio :value="false">{{ t('common.no') }}</el-radio>
      </el-radio-group>
    </el-form-item>
    <!-- 专业分组设置 按专业分组评审时展示 -->
    <el-form-item
      v-if="formData.isMajorGroup"
      key="majorGroupSettings"
      :label="t('templateRule.fields.majorGroupSettings')"
      prop="majorGroupSettings"
    >
      <el-checkbox
        v-for="item in majorGroupSettings"
        v-model="item.selected"
        :key="item.value"
        :label="item.label"
        :checked="item.selected"
        @change="(val: boolean) => onMajorChecked(item, val)"
      />
    </el-form-item>
    <!-- 评审规则 -->
    <el-form-item :label="t('templateRule.fields.judgeRule')" prop="judgeRule">
      <Editor v-model="formData.judgeRule" height="300px" />
    </el-form-item>
    <!-- 晋级名额设置 不是按专业分组评审时才展示 -->
    <template v-if="formData.amountType && !formData.isMajorGroup">
      <CardTitle :title="t('template.stageRules.amountTitle')" class="block mb-10px" />
      <!-- 只有博士和硕士合并的时候显示总名额 -->
      <el-form-item
        v-if="formData.amountType === 4"
        key="totalAmount"
        :label="t('templateRule.fields.totalAmount')"
        prop="totalAmount"
      >
        <el-input-number
          v-model="formData.totalAmount"
          :placeholder="t('common.inputTextPlaceholder') + t('templateRule.fields.totalAmount')"
          class="better-number-input !w-1/1"
          :controls="false"
        />
      </el-form-item>
      <!-- 仅博士或博士硕士并列显示博士名额 -->
      <el-form-item
        v-if="[1, 3].includes(formData.amountType)"
        key="phdAmount"
        :label="t('templateRule.fields.phdAmount')"
        prop="phdAmount"
      >
        <el-input-number
          v-model="formData.phdAmount"
          :placeholder="t('common.inputTextPlaceholder') + t('templateRule.fields.phdAmount')"
          class="better-number-input !w-1/1"
          :controls="false"
        />
      </el-form-item>
      <!-- 仅硕士或博士硕士并列显示硕士名额 -->
      <el-form-item
        v-if="[2, 3].includes(formData.amountType)"
        key="masterAmount"
        :label="t('templateRule.fields.masterAmount')"
        prop="masterAmount"
      >
        <el-input
          v-model="formData.masterAmount"
          :placeholder="t('common.inputTextPlaceholder') + t('templateRule.fields.masterAmount')"
        />
      </el-form-item>
    </template>
    <!-- 得分方式设置 -->
    <!-- <div v-if="formData.judgeType === '3'" class="mx-80px">
      <div class="block text-center font-bold mb-[10px]">得分方式</div>
      <div class="flex gap-12px mb-[10px]">
        <div class="flex-shrink-0 line-height-32px">是否赋分</div>
        <el-radio-group v-model="scoreJson.isAssignScores">
          <el-radio :value="true">{{ t('common.yes') }}</el-radio>
          <el-radio :value="false">{{ t('common.no') }}</el-radio>
        </el-radio-group>
      </div>
      <el-row v-if="scoreJson.isAssignScores" :gutter="30">
        <el-col :span="12">
          <div class="flex gap-12px">
            <div class="flex-shrink-0 line-height-32px">限定年级</div>
            <el-select
              v-model="scoreJson.grade"
              :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.grade')"
              clearable
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_GRADE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </el-col>
        <el-col :span="12">
          <div class="flex gap-12px">
            <div class="flex-shrink-0 line-height-32px">限定培养层次</div>
            <el-select
              v-model="scoreJson.trainingLevel"
              :placeholder="t('common.selectTextPlaceholder') + t('imrStudent.fields.trainingLevel')"
              clearable
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.IMR_INFO_TRAINING_LEVEL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </div>
        </el-col>
      </el-row>
    </div> -->
  </el-form>
</template>

<script setup lang="ts">
import { FormRules } from 'element-plus'
import { LVS, TemplateVO } from '@/api/awards/template'
import { TemplateRuleApi, TemplateRuleVO } from '@/api/awards/templaterule'

defineOptions({ name: 'StageRules' })

const props = defineProps<{
  isInitial: boolean
  templateData: TemplateVO
  rulesData: TemplateRuleVO | undefined
}>()

const { t } = useI18n() // 国际化

const formRef = ref() // 表单 Ref
const formLoading = ref(false)
const formData = ref<any>({
  id: undefined,
  templateId: undefined,
  judgeType: '1',
  judgeStage: undefined,
  amountType: 1,
  isDrawToNext: false,
  isDebate: true,
  isMajorGroup: false,
  majorGroupSettings: undefined,
  scoreJson: undefined,
  judgeRule: undefined,
  totalAmount: undefined,
  phdAmount: undefined,
  masterAmount: undefined,
  remark: undefined
})
const formRules = reactive<FormRules>({
  judgeType: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('templateRule.fields.judgeType'),
      trigger: 'blur'
    }
  ],
  isDebate: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('templateRule.fields.isDebate'),
      trigger: 'blur'
    }
  ],
  amountType: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('templateRule.fields.amountType'),
      trigger: 'blur'
    }
  ],
  isDrawToNext: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('templateRule.fields.isDrawToNext'),
      trigger: 'blur'
    }
  ],
  isMajorGroup: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('templateRule.fields.isMajorGroup'),
      trigger: 'blur'
    }
  ],
  majorGroupSettings: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('templateRule.fields.majorGroupSettings'),
      trigger: 'blur'
    }
  ],
  judgeRule: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('templateRule.fields.judgeRule'),
      trigger: 'blur'
    }
  ],
  totalAmount: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('templateRule.fields.totalAmount'),
      trigger: 'blur'
    }
  ],
  phdAmount: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('templateRule.fields.phdAmount'),
      trigger: 'blur'
    }
  ],
  masterAmount: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('templateRule.fields.masterAmount'),
      trigger: 'blur'
    }
  ]
})

// 专业分组设置
const majorGroupSettings = ref<LVS[]>([
  {
    label: '材料物理与化学',
    value: '材料物理与化学',
    selected: true
  },
  {
    label: '材料学',
    value: '材料学',
    selected: true
  },
  {
    label: '材料加工工程',
    value: '材料加工工程',
    selected: true
  },
  {
    label: '腐蚀科学与防护',
    value: '腐蚀科学与防护',
    selected: true
  }
])

// // 打分方式选项
// const scoringTypeOptions = ref([
//   {
//     label: '科研工作',
//     value: '科研工作'
//   }
// ])
// // 赋分方式选项
// const assignScoreTypeOptions = ref([
//   {
//     label: '思想品德',
//     value: '思想品德'
//   },
//   {
//     label: '课程学习成绩',
//     value: '课程学习成绩'
//   }
// ])
//
// // 得分方式配置
// const scoreJson = ref<ScoreJson>({
//   isAssignScores: true,
//   masterScoring: {
//     type: '科研工作',
//     proportion: 40
//   },
//   masterAssignScore: {
//     type: '思想品德',
//     proportion: 10
//   },
//   phdScoring: {
//     type: '科研工作',
//     proportion: 90
//   },
//   phdAssignScore: {
//     type: '思想品德',
//     proportion: 10
//   },
//   trainingLevel: '',
//   grade: '',
// })

// 名额类型改变
const onAmountTypeChange = (val: number) => {
  // 如果是博士和硕士合并
  if (val === 4) {
    formData.value.phdAmount = undefined
    formData.value.masterAmount = undefined
  } else if (val === 1 || val === 3) {
    formData.value.masterAmount = undefined
  } else if (val === 2) {
    formData.value.phdAmount = undefined
  }
}

// 重置专业分组设置
const resetMajorGroupSettings = (val: boolean) => {
  // 重置专业分组设置
  majorGroupSettings.value.forEach((item) => {
    item.selected = false
  })
  // 重置所有名额
  formData.value.totalAmount = undefined
  formData.value.phdAmount = undefined
  formData.value.masterAmount = undefined
  // 如果设置了不按专业分组评审
  if (!val) {
    formData.value.majorGroupSettings = undefined
  }
}

// 专业分组设置选中
const onMajorChecked = (item: LVS, val: boolean) => {
  // 设置选中状态
  item.selected = val
  // 设置专业分组设置
  formData.value.majorGroupSettings = JSON.stringify(majorGroupSettings.value)
}

// 提交数据
const submit = async (templateId: string) => {
  await formRef.value.validate()
  const data = formData.value as unknown as TemplateRuleVO
  data.templateId = templateId
  if (data.id) {
    await TemplateRuleApi.updateTemplateRule(data)
  } else {
    await TemplateRuleApi.createTemplateRule(data)
  }
}

const resetForm = () => {
  formData.value = {
    id: undefined,
    templateId: undefined,
    judgeType: '1',
    judgeStage: undefined,
    amountType: 1,
    isDrawToNext: false,
    isDebate: true,
    isMajorGroup: false,
    majorGroupSettings: undefined,
    scoreJson: undefined,
    judgeRule: undefined,
    totalAmount: undefined,
    phdAmount: undefined,
    masterAmount: undefined,
    remark: undefined
  }
  formRef.value.resetFields()

  majorGroupSettings.value.forEach((item) => {
    item.selected = false
  })
}

const initData = async () => {
  if (props.rulesData) {
    formData.value = props.rulesData
    await nextTick()
    // 如果有专业分组设置
    if (props.rulesData.majorGroupSettings) {
      try {
        // majorGroupSettings.value = JSON.parse(props.rulesData.majorGroupSettings)
        const majors = JSON.parse(props.rulesData.majorGroupSettings).filter(
          (item) => item.selected
        )
        majorGroupSettings.value.forEach((item) => {
          item.selected = majors.some((major: LVS) => major.value === item.value)
        })
      } catch {}
    }
    return
  }
  if (props.isInitial) {
    formData.value.isDrawToNext = true
    formData.value.judgeStage = '1'
  } else {
    formData.value.isDrawToNext = undefined
    formData.value.judgeStage = '2'
  }
}

// 如果选了排序 并且名额类型是并列 那么清空并列(排序下不让并列)
const cleanCoordinateIfTypeSort = () => {
  if (formData.value.judgeType === '2') {
    if (formData.value.amountType === 3) {
      formData.value.amountType = undefined
    }
  }
}

// 暴露方法
defineExpose({
  initData,
  resetForm,
  submit,
  validate: () => formRef.value.validate()
})
</script>

<style scoped lang="scss"></style>
